#import <appkit/appkit.h>

BOOL
transcribeImageFromFileToCFile(char vname[], char in[], char out[])
{
  BOOL                ret = NO;

  FILE               *f;

  if ((f = fopen(in, "r")) != NULL)
  {
	unsigned char       i;

	int                 count = 0;
	NXStream           *s = NULL;

	s = NXOpenMemory(NULL, 0L, NX_WRITEONLY);

	NXPrintf(s, "static unsigned char %s_buf[] = {\n", vname);
	while (fread(&i, sizeof(unsigned char), (size_t)1, f) == 1)
	{
	  int                 o = (int)i;

	  NXPrintf(s, "0x%02hx, ", o);
	  
	  count += 1;
	  if ((count % 10) == 0)
	  {
		NXPrintf(s, "\n");
	  }
	}

	NXPrintf(s, "\n};\n\n");
	NXPrintf(s, "NXImage *\n%s_fn(void)\n", vname);
	NXPrintf(s, "{\n");
	NXPrintf(s, "  NXImage *ret = nil;\n");
	NXPrintf(s, "  NXStream *stream = NXOpenMemory(%s_buf, sizeof(%s_buf), NX_READONLY);\n", vname, vname);
	NXPrintf(s, "  ret = [[NXImage alloc] initFromStream:stream];\n");
	NXPrintf(s, "  NXCloseMemory(stream, NX_FREEBUFFER);\n");
	NXPrintf(s, "  return ret;\n");
	NXPrintf(s, "}\n\n");
	
	if (NXSaveToFile(s, out) == 0)
	{
	  ret = YES;
	}
	NXCloseMemory(s, NX_FREEBUFFER);
  }
  return ret;
}

int
main(int argc, char *argv[])
{
  BOOL                verbose = YES;

  if (argc < 2)
  {
	fprintf(stderr, "Usage: %s [-h] [-s] filename {filename ...}\n", argv[0]);
	exit(1);
  } else
  {
	int                 i;

	for (i = 1; i < argc; i++)
	{
	  if (strcmp(argv[i], "-h") == 0)
	  {
		fprintf(stderr, "Usage: %s [-h] [-s] filename {filename ...}\n", argv[0]);
		fprintf(stderr, "-h\tprint this message\n");
		fprintf(stderr, "-s\tdo not print out progress verbosely\n");
	  } else
	  if (strcmp(argv[i], "-v") == 0)
	  {
		verbose = NO;
	  } else
	  {
		BOOL                err;
		char               *dot;

		char 				vname[MAXPATHLEN + 1];
		char                pathname[MAXPATHLEN + 1];

		strcpy(vname, argv[i]);

		if ((dot = strrchr(vname, '.')) != NULL)
		{
		  if (strcmp(dot, ".tiff") != 0 &&
			  strcmp(dot, ".TIFF") != 0 &&
			  strcmp(dot, ".eps") != 0 &&
			  strcmp(dot, ".EPS") != 0)

		  {
			if (verbose)
			{
			  fprintf(stderr, "error: %s not a TIFF or EPS file.\n", argv[i]);
			}
			continue;
		  }
		}

		while ((dot = strchr(vname, '.')) != NULL)
		{
		  *dot = '_';
		}
		strcpy(pathname, vname);
		strcat(pathname, ".m");

		if (verbose)
		{
		  fprintf(stderr, "working: %s --> ", argv[i]);
		}

		err = transcribeImageFromFileToCFile(vname, argv[i], pathname);

		if (verbose)
		{
		  fprintf(stderr, "%s (%s).\n", pathname, (err) ? "OK" : "ERROR");
		}
	  }
	}
  }
  return 0;
}
